//引入即可
require("module-alias/register");
require("./task-schedules/index"); // task任务
const path = require("path");
const Koa = require("koa");
const Router = require('koa-router');
const convert = require("koa-convert");
const bodyParser = require("koa-bodyparser");
const validate = require("koa-validate");
const koaStatic = require("koa-static");
const AppConfig = require("$config/app.config");
const logger = require("$logger");
const apiRouter = new Router();
const router = require("./routes");
const mysql = require("@/db/mysql");
const fileDownloadMiddleware = require("@/middleware/file-download.middleware");
const jwtMiddleware = require("@/middleware/jwt.middleware");
const tenantsMiddleware = require("@/middleware/tenants.middleware");
const operationLoggerMiddleware = require("@/middleware/operation-logger.middleware");
const startUp = require("./startup");

const app = new Koa();

// 关键配置：信任代理头（否则 ctx.ip 会是 Nginx 的 IP）
app.proxy = true; // 信任 proxy 头（X-Forwarded-For）

// 使用jwt中间件
app.use(jwtMiddleware);

// 租户中间件
app.use(tenantsMiddleware);

// 请求体中间件
app.use(convert(bodyParser()));

// 操作日志中间件
app.use(operationLoggerMiddleware({
    pool: mysql
}));

// 文件访问
app.use(koaStatic(path.join("./")));

// 文件下载中间件
router.get("/downloads/:code/:filename", fileDownloadMiddleware);

// 使用参数验证中间件
validate(app);
// app.use(defineValidator());
// app.use();

// 解析body file文件
// app.use(koaBody({
//   multipart: true,
//   parsedMethods: ["POST", "PUT", "PATCH", "DELETE"], // 只解析这些方法的body
// }))

apiRouter.use('/api/v1', router.routes(), router.allowedMethods());

// 使用路由
app.use(apiRouter.routes());
app.use(apiRouter.allowedMethods());


app.listen(AppConfig.PORT, () => {
    logger.success(`App running in ${process.env.NODE_ENV} mode`);
	logger.warning(`Server running on http://localhost:${AppConfig.PORT}`);
	startUp();
    require("./crawlers/tobacco/index");
});
